/**
 * Created by xxx on 2017/6/14.
 */
//用react封装
var currentpage = 1,totalpage = 1,i;//分页的当前页和总的页数 手机号码格式是否正确
var tableData = [],importRepeatData = [];
//表单的最高高度、当前第几页、总页数、总行数
var otherData = {pageLeft:0,pageRight:0};
//分页
var Page = React.createClass({
    setPage: function (e) {
        setPage($(e.target).html());
        this.props.onPageClick(1);
    },
    showPage: function () {
        showPage();
    },
    render: function () {
        {
            var items = [],
                svar = this;
            if(totalpage == 0 ){
                items.push({num:1,checked:true})
            }else if(totalpage < 6){
                for(i = 1;i <= totalpage ;i++) {
                    if (i == currentpage) {
                        items.push({num:i,checked:true})
                    } else {
                        items.push({num:i,checked:false})
                    }
                }
            }else if(currentpage >= (totalpage-2)) {//点在左边
                items.push({num:1,checked:false});
                items.push({num:'···',checked:false});
                for(i = totalpage-2;i <= totalpage ;i++){
                    if(i == currentpage){
                        items.push({num:i,checked:true})
                    }else{
                        items.push({num:i,checked:false})
                    }
                }
            }else if(currentpage <= 3){
                for(i = 1;i <= 3 ;i++) {
                    if (i == currentpage) {
                        items.push({num:i,checked:true})
                    } else {
                        items.push({num:i,checked:false})
                    }
                }
                items.push({num:'···',checked:false});
                items.push({num:totalpage,checked:false})
            }else {//点在两边
                items.push({num:1,checked:false});
                items.push({num:'···',checked:false});
                items.push({num:currentpage-1,checked:false});
                items.push({num:currentpage,checked:true});
                items.push({num:currentpage+1,checked:false});
                items.push({num:'···',checked:false});
                items.push({num:totalpage,checked:false})
            }
        }
        return (
            <div className="tableInfo-page">
                <div className="page-number">每页<span className="page-number-list" onClick={this.showPage}>{pagecount}</span>条</div>
                <div className="page-list" style={{top:pageListTop+"px"}}>
                    <ul>
                        {
                            pageList.map(function (item) {
                                return (<li onClick={svar.setPage}>{item}</li>)
                            })
                        }
                    </ul>
                </div>
                <div className="page-limit">
                    <ol className="page-limit-ol">
                        <li className="page-limit-img" name="-1" onClick={otherData.pageLeft == 0?'':svar.props.onPageClick.bind(svar,-1)}><span className={otherData.pageLeft == 0?'page-limit-left-no':'page-limit-left-yes'}/></li>
                        {
                            items.map(function (item) {
                                return (<li onClick={isNaN(item.num)?'':svar.props.onPageClick.bind(svar,item.num)}  className={item.checked == true?'page-limit-num page-limit-checked':'page-limit-num'} name={item.num}>{item.num}</li>)
                            })
                        }
                        <li className="page-limit-img" name="-2" onClick={otherData.pageRight == 0?'':svar.props.onPageClick.bind(svar,-2)}><span className={otherData.pageRight == 0?'page-limit-right-no':'page-limit-right-yes'}/></li>
                    </ol>
                </div>
            </div>
        );
    }
});
//表单组件
var Table = React.createClass({
    render: function () {
        return (
            <tr>
                <td style={{width: '6%'}}>{parseInt(this.props.listNumber)+1}</td>
                <td style={{width: '8%'}}>{this.props.id}</td>
                <td style={{width: '8%'}}>{this.props.name}</td>
                <td style={{width: '8%'}}>{this.props.code}</td>
                <td style={{width: '12%'}}>{this.props.url}</td>
                <td style={{width: '10%'}}>{this.props.parentId==null?'无':this.props.parentId}</td>
                <td style={{width: '10%'}}>{this.props.num==null?'无':this.props.num}</td>
                <td style={{width: '10%'}}>{this.props.isLeaf=='0'?'否':'是'}</td>
                <td style={{width: '9%'}}>{this.props.menutype=='1'?'菜单权限':'功能权限'}</td>
                <td style={{width: '9%'}}>{this.props.icon == null?'无':(this.props.icon==''?'无':this.props.icon) }</td>
                <td style={{width: '10%'}}><div className="trButton trLeft " onClick={this.props.onClickEdit}>修改</div><div className="trButton trLeft table-delete" onClick={this.props.onClickDelete}>删除</div></td>
            </tr>
        );
    }
});
//父组件
var Main = React.createClass({
    //组件初始状态
    getInitialState: function () {
        return {
            otherData:this.props.otherData,
            tableData:this.props.tableData,
            importRepeatData:this.props.importRepeatData,
            popTitle:'',
        }
    },
    componentDidMount: function () {
        //使用ajax取出数据然后组装数据列表
        var svar = this;
        suixun.ajax(serverUrl+'/menuManager/getMenuPage.json?param={index:1,num:"'+pagecount+'"}','',"get",function(data){
            setTimeout(function () {
                suixun.hideLoding();//隐藏加载中
            },200);
            if(data.code == 200){
                for(var i=0;i<data.info.list.length;i++){
                    var obj=data.info.list[i];
                    tableData[i] = {keyid:i,id:obj.id,name:obj.name,code:obj.code,url:obj.url,parentId:obj.parentId,num:obj.num,isLeaf:obj.isLeaf,menutype:obj.menutype,icon:obj.icon};
                }
                var pageRight = 0;
                if(data.info.totalpage > 1){
                    pageRight = 1
                }
                otherData = {pageLeft:0,pageRight:pageRight};
                currentpage = 1;totalpage = data.info.totalpage;//初始化的时候赋值：分页的当前页和总的页数
                svar.setState({tableData:tableData,otherData:otherData});
            }
        });
        //绑定回车时间
        $(document).keypress(function(e) {
            var eCode = e.keyCode ? e.keyCode : e.which ? e.which : e.charCode;
            if (eCode == 13){
                if($(".enterEvent").is(":focus")){
                    svar.onClickQuery();
                }
            }
        });
    },
    /**
     * 搜索查询
     */
    onClickQuery: function () {
        this.onPageClick(1);
    },
    /**
     * 分页查询
     * @param num
     */
    onPageClick: function (num) {
        //分页-调用ajac然后把数据查询出来:获取name的值
        //计算currentpage
        var onPageLeft = 0,onPageRight = 1,savr = this;
        if(num > 0){
            currentpage = num;
        }else if(num == -1 && currentpage > 1){
            currentpage --;
        }else if(num == -2  && currentpage < totalpage){
            currentpage ++;
        }else{
            return;
        }
        //修改左右的按钮
        if((currentpage == totalpage && totalpage == 1)|| totalpage == 0){
            onPageLeft = 0;
            onPageRight = 0;
        }else if(currentpage == totalpage && totalpage > 1){
            onPageLeft = 1;
            onPageRight = 0;
        }else if(1 < currentpage && currentpage < totalpage){
            onPageLeft = 1;
            onPageRight = 1;
        }
        var param="param={";
        suixun.showLoding();//显示加载中
        param = getJsonDataNotEmpty(param,"name",$('.enterEvent').val()+'');
        param = getJsonDataNotEmpty(param,"index",+currentpage+'');
        param = getJsonDataNotEmpty(param,"num",pagecount+'');
        param += "}";
        suixun.ajax(serverUrl+'/menuManager/getMenuPage.json',param,"get",function(data){
            tableData = [];
            suixun.hideLoding();//隐藏加载中
            if(data.code == 200){
                if(data.info.list != null){
                    for(var i=0;i<data.info.list.length;i++){
                        var obj=data.info.list[i];
                        tableData[i] = {keyid:i,id:obj.id,name:obj.name,code:obj.code,url:obj.url,parentId:obj.parentId,num:obj.num,isLeaf:obj.isLeaf,menutype:obj.menutype,icon:obj.icon};
                    }
                    if(data.info.totalpage > 1 && data.info.totalpage > currentpage){
                        onPageRight = 1
                    }else{
                        onPageRight = 0;
                    }
                    otherData = {pageLeft:onPageLeft,pageRight:onPageRight};
                    totalpage = data.info.totalpage;//初始化的时候赋值：分页的当前页和总的页数
                    savr.setState({tableData:tableData,otherData:otherData});
                }else{
                    totalpage = 1;//初始化的时候赋值：分页的当前页和总的页数
                    savr.setState({tableData:[],otherData:{pageLeft:0,pageRight:0}});
                }

            }
        });
    },
    onClickHidePop: function () {
        $("#inputExcelName").val("");
        $("#file").val("");
        $(".errorMsg").hide();
        $(".popModel").hide();
    },

    /**
     * 删除
     * @returns {XML}
     * @param id
     */
    onClickDelete: function (id) {
        var svar = this;
        var param="param={";
        param = getJsonDataNotEmpty(param,"ids",'"'+id+'"');
        param += "}";
        suixun.confirm_noTit('是否确定删除?',function (data) {
            if(data == true){
                suixun.ajax(serverUrl+'/menuManager/removeMenu.json',param,"get",function(data){
                    if(data.code == 200){
                        suixun.alert('删除成功！',function (data) {
                            if(data){
                                svar.onPageClick(currentpage);
                            }
                        });
                    } else {
                        suixun.alert(data.msg);
                    }
                });
            }
        });
    },
    /**
     * 编辑修改
     * @returns {XML}
     * @param info
     */
    onClickEdit:function (info) {
        $("#menuId").val(info[0]);
        $("#menuName").val(info[1]);
        $("#menuCode").val(info[2]);
        $("#menuUrl").val(info[3]);
        $("#menuParId").val(info[4]);
        $("#menuNumer").val(info[5]);
        $(":radio[name='isChildMenu'][value='" + info[6] + "']").prop("checked", "checked");
        $(":radio[name='menuType'][value='" + info[7] + "']").prop("checked", "checked");
        $("#menuImg").val(info[8]);
        this.setState({popTitle:'修改权限菜单'});
        $('.popPoppermissions').show();
        $(".errorMsg").hide();
    },
    /**
     * 验证
     * @returns {XML}
     * @param e
     */
    onBlurInput: function (e) {
        var classname = e.target.getAttribute("data-error");
        if($(e.target).val() == ''){
            $("."+classname+"").show();
        }else{
            $("."+classname+"").hide();
        }
    },
    /**
     * 编辑-保存
     * @returns {XML}
     */
    onClickSaveEdit: function () {
        var menuId = $("#menuId").val(),
            menuName = $("#menuName").val(),
            menuCode = $("#menuCode").val(),
            menuUrl = $("#menuUrl").val(),
            menuParId = $("#menuParId").val(),
            menuNumer = $("#menuNumer").val(),
            isChildMenu = $("input[name='isChildMenu']:checked").val(),
            menuType = $("input[name='menuType']:checked").val(),
            menuImg = $("#menuImg").val();
        if(menuName == ""){
            suixun.alert("权限名称不能为空");
            return;
        }
        if(menuCode == ""){
            suixun.alert("菜单code不能为空");
            return;
        }
        if(menuUrl == ""){
            suixun.alert("资源url不能为空");
            return;
        }
        if(isChildMenu == undefined){
            isChildMenu = '';
        }
        if(menuType == undefined){
            menuType = '';
        }
        suixun.showLoding();//显示加载中
        var svar = this;
        var param="param={";
        if(this.state.popTitle == '修改权限菜单'){
            param = getJsonDataNotEmpty(param,"id",menuId+'');
        }
        param = getJsonDataNotEmpty(param,"name",'"'+menuName+'"');
        param = getJsonDataNotEmpty(param,"code",'"'+menuCode+'"');
        param = getJsonDataNotEmpty(param,"url",'"'+menuUrl+'"');
        param = getJsonDataNotEmpty(param,"parentId",menuParId+'');
        param = getJsonDataNotEmpty(param,"num",menuNumer+'');
        param = getJsonDataNotEmpty(param,"isLeaf",isChildMenu+'');
        param = getJsonDataNotEmpty(param,"menutype",menuType+'');
        param = getJsonDataNotEmpty(param,"icon",'"'+menuImg+'"');
        param += "}";
        if(this.state.popTitle == '修改权限菜单'){
            suixun.ajax(serverUrl+'/menuManager/updateMenu.json',param,"get",function(data){
                suixun.hideLoding();//隐藏加载中
                if(data.code == 200){
                    suixun.alert('修改成功！',function (data) {
                        if(data){
                            $(".popPoppermissions").hide();
                            svar.onPageClick(currentpage);
                        }
                    });
                } else {
                    suixun.alert(data.msg);
                }
            });
        }else{
            suixun.ajax(serverUrl+'/menuManager/saveMenu.json',param,"get",function(data){
                suixun.hideLoding();//隐藏加载中
                if(data.code == 200){
                    suixun.alert('新增成功！',function (data) {
                        if(data){
                            $(".popPoppermissions").hide();
                            svar.onPageClick(currentpage);
                        }
                    });
                } else {
                    suixun.alert(data.msg);
                }
            });
        }

    },
    /**
     * 新增权限
     */
    onCilckAdd: function () {
        $("#menuId").val('');
        $("#menuName").val('');
        $("#menuCode").val('');
        $("#menuUrl").val('');
        $("#menuParId").val('');
        $("#menuNumer").val('');
        $("input[name='isChildMenu']:checked").attr("checked",false);
        $("input[name='menuType']:checked").attr("checked",false);
        $("#menuImg").val('');
        this.setState({popTitle:'新增权限菜单'});
        $('.popPoppermissions').show();
    },
    render: function () {
        {
            var svar = this;
            var onClickArray = [this.onClickDelete,this.onClickEdit];
            var Tabels = this.state.tableData.map(function (data,index) {
                return (
                    <Table  key={index} onClickDelete={onClickArray[0].bind(svar,data.id)} onClickEdit={onClickArray[1].bind(svar,[data.id,data.name,data.code,data.url,data.parentId,data.num,data.isLeaf,data.menutype,data.icon])} listNumber={index} id={data.id} name={data.name}
                            code={data.code} url={data.url} parentId={data.parentId}   num={data.num} isLeaf={data.isLeaf} menutype={data.menutype} icon={data.icon} />
                )
            });
        }
        return (
            <div className="tableManage-body">
                <div  className="popPhone pop popModel popPoppermissions">
                    <div className="model"></div>
                    <div className="popModel-info popTeacher-info">
                        <div className="popModel-title">
                            <span className="popModel-title-content">
                                <span className="popModel-title-content-solid-left"/>
                                {this.state.popTitle}
                                <span className="popModel-title-content-solid-right"/>
                            </span>
                            <span className="popModel-title-img" onClick={this.onClickHidePop}><img src="../img/icon/close.png" alt="关闭"/></span>
                        </div>
                        <div className="popModel-body">
                            <input type="hidden" id="menuId"/>
                            <div className="popModel-body-input">
                                <span className="popModel-body-input-title">权限名称</span>
                                <span className="popModel-body-input-content">
                                    <input className="input-content " data-error="menuName-error" onBlur={this.onBlurInput}  maxLength="100" id="menuName" type="text" placeholder="请输入权限名称" />
                                </span>
                                <div className="errorMsg menuName-error" ></div>
                            </div>
                            <div className="popModel-body-input">
                                <span className="popModel-body-input-title">菜单code</span>
                                <span className="popModel-body-input-content">
                                    <input className="input-content " data-error="menuCode-error" onBlur={this.onBlurInput}  maxLength="200" id="menuCode" type="text" placeholder="请输入菜单code" />
                                </span>
                                <div className="errorMsg menuCode-error" ></div>
                            </div>
                            <div className="popModel-body-input">
                                <span className="popModel-body-input-title ">资源url</span>
                                <span className="popModel-body-input-content">
                                    <input className="input-content "  data-error="menuUrl-error" onBlur={this.onBlurInput} maxLength="300" id="menuUrl" type="text" placeholder="请输入资源url" />
                                </span>
                                <div className="errorMsg menuUrl-error" ></div>
                            </div>
                            <div className="popModel-body-input">
                                <span className="popModel-body-input-title noImg">父类菜单id</span>
                                <span className="popModel-body-input-content">
                                    <input className="input-content "   maxLength="30" id="menuParId" type="text" placeholder="请输入父类菜单id" />
                                </span>
                            </div>
                            <div className="popModel-body-input">
                                <span className="popModel-body-input-title noImg">菜单顺序号</span>
                                <span className="popModel-body-input-content">
                                    <input className="input-content "   maxLength="30" id="menuNumer" type="text" placeholder="请输入菜单顺序号" />
                                </span>
                            </div>
                            <div className="popModel-body-input">
                                <span className="popModel-body-input-title noImg" >是否是子菜单</span>
                                <span className="popModel-body-radio-content "><input name="isChildMenu" value="1" type="radio" /><span>是</span></span>
                                <span className="popModel-body-radio-content " style={{left:'40px'}}><input name="isChildMenu" value="0" type="radio" /><span>否</span></span>
                            </div>
                            <div className="popModel-body-input">
                                <span className="popModel-body-input-title noImg" >权限类型</span>
                                <span className="popModel-body-radio-content "><input name="menuType" value="1" type="radio" /><span>菜单权限</span></span>
                                <span className="popModel-body-radio-content " style={{left:'40px'}}><input name="menuType" value="2" type="radio" /><span>功能权限</span></span>
                            </div>
                            <div className="popModel-body-input">
                                <span className="popModel-body-input-title noImg">菜单图标</span>
                                <span className="popModel-body-input-content">
                                    <input className="input-content "  maxLength="50" id="menuImg" type="text" placeholder="请输入菜单图标" />
                                </span>
                            </div>
                        </div>
                        <div className="popModel-button">
                            <span className="popModel-button-ok" onClick={this.onClickSaveEdit}>确定</span>
                        </div>
                    </div>
                </div>
                <header>
                    <div className="header-left">
                        <div className="header-left-query">
                            <div className="header-left-query-input">
                                <input className="queryVal enterEvent" type="text" placeholder="请输入权限名称" onInput={this.onInputNumber} />
                                <input type="hidden" name="sim-status" id="sim-status"/>
                            </div>
                            <div className="header-left-query-img" onClick={this.onClickQuery}></div>
                        </div>
                    </div>
                    <div className="header-right">
                        <div className="addButton" style={{width:"140px",height:'35px'}} onClick={this.onCilckAdd}>
                            <span className="addButton-img" style={{left: "-48px",top:'1px'}}><img src="../img/icon/add-white.png" /></span>
                            <span className="addButton-text" style={{width:"100px",left:"33px",top:'-7px'}}>新增权限菜单</span>
                        </div>
                    </div>
                </header>
                <div className="parentsInfo tableInfo">
                    <div className="parentsInfo-data tableInfo-data">
                        <div className="parentsInfo-data-table tableInfo-data-table" >
                            <table className="head-body head-body">
                                <thead>
                                    <th style={{width: '6%'}}>序号</th>
                                    <th style={{width: '8%'}}>菜单id</th>
                                    <th style={{width: '8%'}}>权限名称</th>
                                    <th style={{width: '8%'}}>菜单code</th>
                                    <th style={{width: '12%'}}>资源url</th>
                                    <th style={{width: '10%'}}>父类菜单id</th>
                                    <th style={{width: '10%'}}>菜单顺序号</th>
                                    <th style={{width: '10%'}}>是否是子菜单</th>
                                    <th style={{width: '9%'}}>权限类型</th>
                                    <th style={{width: '9%'}}>菜单图标</th>
                                    <th style={{width: '10%'}}>操作</th>
                                </thead>
                                <tbody>
                                {this.state.tableData==""?'':Tabels}
                                </tbody>
                            </table>
                            {this.state.tableData==""?<div className="tableNoData">{tableNoDataCount}</div>:''}
                        </div>
                    </div>
                    <Page otherData={this.state.otherData} onPageClick={this.onPageClick} />
                </div>
                <footer id="copyright">
                    <span><img src="../img/icon/copyright.png"/>{copyright}</span>
                </footer>
            </div>
        );
    }
});
ReactDOM.render(
    <Main  otherData={otherData} tableData={tableData} importRepeatData={importRepeatData}  />,
    document.getElementById('tableManage')
);
//学校下拉列表
$("*").bind("click",function(e){
    var target = $(e.target);
    if(target.closest(".schoolList-value").length == 1){
        $("#schoolname_search").val(target.html());
    }
    $(".schoolList").hide();
});
